package com.party.jackclientandroid.ui_home.activity;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.MyCommonAdapter;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.base.BaseFragmentFilter;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.BlackCardItem;
import com.party.jackclientandroid.utils.DistanceUtil;
import com.party.jackclientandroid.utils.TimeUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.iwgang.countdownview.CountdownView;

/**
 * 黑卡专区界面<br>
 */
public class BlackCardFragment extends BaseFragmentFilter {
    @BindView(R.id.btn_back)
    View btn_back;
    @BindView(R.id.tv_delete_search_content)
    ImageView tv_delete_search_content;

    List<BlackCardItem> dataList = new ArrayList<>();
    MyCommonAdapter<BlackCardItem> commonAdapter;
    int page = 1;
    int pageSize = Constant.PAGE_SIZE;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_filter_full;
    }

    @OnClick(R.id.btn_back)
    public void mLeftBtn(View view) {
        getActivity().finish();
    }


    @Override
    public void initData() {
        super.initData();
        btn_back.setVisibility(View.VISIBLE);
        initFilterLayout();
        mRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        commonAdapter = new MyCommonAdapter<BlackCardItem>(mActivity, R.layout.item_second_kill_coupon2, dataList) {
            @Override
            protected void convert(ViewHolder holder, final BlackCardItem item, int position) {
                holder.setText(R.id.shop_name_tv, item.getShopName());
                // 秒杀券显示homeImg
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mActivity, item.getCouponImg(), holder.getView(R.id.coupon_iv));
                holder.setText(R.id.coupon_name_tv, item.getOriginalPrice() + "代金券");
                holder.setText(R.id.remain_count_tv, "还剩" + item.getStockCount() + "次");
                holder.setText(R.id.buy_price_tv, "¥" + item.getBuyPrice());
                ProgressBar progressBar = holder.getView(R.id.progress_bar);
                progressBar.setMax(item.getTotal());
                double distance = DistanceUtil.getDistance(mApplication.getMap().getLongitude(),
                        mApplication.getMap().getLatitude(), item.getLongitude(), item.getLatitude());
                holder.setText(R.id.distance_tv, item.getSymbolBuild() + " " + DistanceUtil.handleDistance(distance));
                //int total = item.getTotal();
                //int remainCount = total - item.getItemSalesSum();
                progressBar.setProgress(item.getItemSalesSum());
                holder.setText(R.id.original_price_tv, "¥" + item.getOriginalPrice());
                //holder.setText(R.id.distance_tv,item.getSymbolBuild());
                holder.setOnClickListener(R.id.now_rob_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, SecondKillCouponDetailActivity.class);
                        intent.putExtra("couponId", item.getId());
                        startActivity(intent);
                    }
                });
                //处理剩余时间
                CountdownView countdownView = holder.getView(R.id.count_down_view);
                LinearLayout remain_time_ll = holder.getView(R.id.remain_time_ll);
                TextView remain_date_tv1 = holder.getView(R.id.remain_date_tv1);
                TextView remain_date_tv2 = holder.getView(R.id.remain_date_tv2);
                TextView remain_date_tv3 = holder.getView(R.id.remain_date_tv3);
                LinearLayout remain_date_ll = holder.getView(R.id.remain_date_ll);
                long currTimeStamp = TimeUtil.getCurrTimeStamp();
                long endTimeStamp = item.getEndSaleTime();
                long remainTimeStamp = endTimeStamp - currTimeStamp;
                if (remainTimeStamp <= 0) {
                    remain_time_ll.setVisibility(View.GONE);
                    remain_date_ll.setVisibility(View.VISIBLE);
                    remain_date_tv1.setText("已");
                    remain_date_tv2.setText("结");
                    remain_date_tv3.setText("束");
                } else if (remainTimeStamp <= 24 * 3600 * 1000) {
                    countdownView.start(remainTimeStamp);
                    remain_time_ll.setVisibility(View.VISIBLE);
                    remain_date_ll.setVisibility(View.GONE);
                } else {
                    remain_time_ll.setVisibility(View.GONE);
                    remain_date_ll.setVisibility(View.VISIBLE);
                    remain_date_tv1.setText("剩");
                    remain_date_tv2.setText(TimeUtil.getRemainTime(remainTimeStamp));
                    remain_date_tv3.setText("天");
                }
            }
        };
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(commonAdapter);
    }

    @Override
    public void initListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                handleItemClick(position);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return true;
            }
        });
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getNeedData();
            }
        });
        getNeedData();
    }

    /**
     * item点击事件
     *
     * @param position
     */
    private void handleItemClick(int position) {
        Intent intent = new Intent(mActivity, SecondKillCouponDetailActivity.class);
        intent.putExtra("couponId", dataList.get(position).getId());
        startActivity(intent);
    }

    /**
     * 下拉获取数据
     */
    public void getNeedData() {
        super.getNeedData();
        addDisposableIoMain(searchService.getCouponsBackCards(page, pageSize, longitude, latitude, areaId, needSearchKey, categoryId, conditionType, jsonDataStr), new DefaultConsumer<List<BlackCardItem>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<BlackCardItem>> baseBean) {
                commonAdapter.clear(page);
                commonAdapter.addData(baseBean.getData());
                commonAdapter.finishLoading(page, pageSize, baseBean.getData().size(), mRefreshLayout);
                finishData(commonAdapter.getDatas());
            }
        });
    }

    /**
     * 加载更多
     */
    private void loadMoreData() {
        page++;
        getNeedData();
    }

}
